package y2016.date0212.pm.图片批量下载;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

public class DownloadImage {
    private String savePath;
    private String saveName;
    private String attr;
    private String value;
    private String attrKey;
    private String valueValue;
    private String attrValue;
    private String htmlPageUrl;
    private String[] htmlSplits;

    public void setSaveName(String saveName) {
        this.saveName = saveName;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    /**
     * 规律是数字的
     *
     * @param urlAdapte url适配格式，例如：http://hao123.wo*.jpg
     * @param start     起始
     * @param end       结束
     */
    public void downloadByLink(String urlAdapte, int start, int end) {
        for (int i = start; i <= end; i++) {
            String urlStr = urlAdapte.replace("*", i + "");
            urlStr = modifiedLink(urlStr);

            if (saveName == null) {    //如果没有指定文件的保存名称，则生成一个
                int index = urlStr.lastIndexOf("/");
                saveName = urlStr.substring(index + 1);
            }
            if (saveName.contains(".")) {
                saveName = saveName.replace(".", i + ".");
            } else {
                saveName = saveName + i;
            }

            File file = new File(savePath, saveName);
            if (file.exists()) {
                System.out.println("失败:" + saveName + "在" + savePath + "已经存在...");
            } else {

                downloada(file, urlStr);

            }
        }
    }

    public void setAttr(String attrKey, String attrValue) {
        this.attrKey = attrKey;
        this.attrValue = attrValue;
    }

    /**
     * @param htmAdapte 网页地址适配格式，例如：http://360.wo*.html
     * @param start     起始页
     * @param end       结束页
     */
    public void getFileByHtmlLink(String htmlAdapte, int start, int end) {
        int j = 1;
        String saveName;
        for (int i = start; i <= end; i++) {
            htmlPageUrl = htmlAdapte.replace("*", i + "");
            htmlSplits = htmlPageUrl.split("/");

            try {
                Document doc = Jsoup.connect(htmlPageUrl).get();
                Elements imgs = doc.getElementsByAttributeValue(attrKey, attrValue);
                String htmlLink = null;
                for (Iterator<Element> iterator = imgs.iterator(); iterator.hasNext(); ) {
                    System.out.println("下载地址：" + htmlLink);
                    Element img = (Element) iterator.next();
                    htmlLink = img.attr("src");
                    htmlLink = modifiedLink(htmlLink);
                    System.out.println(htmlLink);
                    if (this.saveName == null) {
                        saveName = htmlLink.substring(htmlLink.lastIndexOf("/") + 1);
                        this.saveName = saveName;
                    }
                    if (this.saveName.contains(".")) {
                        saveName = this.saveName.replace(".", j + ".");
                    } else {
                        saveName = this.saveName + j;
                    }
                    j++;

                    File downloadFile = new File(savePath, saveName);
                    if (downloadFile.exists()) {
                        System.out.println("失败，" + saveName + "在" + savePath + "已存在...");
                    } else {
                        downloada(downloadFile, htmlLink);
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private String htmlUrl(int splitIndex) {
        StringBuilder sb = new StringBuilder();
        int opsition = splitIndex;
        if (opsition > htmlSplits.length) {
            opsition = htmlSplits.length;
        }

        for (int i = 0; i < opsition; i++) {
            sb.append(htmlSplits[i] + "/");
        }
        return sb.toString();
    }

    /**
     * 去除不正确格式
     *
     * @param htmlLink
     * @return
     */
    private String modifiedLink(String htmlLink) {
        String url = null;
        if (htmlLink.startsWith("../")) {
            url = htmlUrl(htmlSplits.length - 2);
            htmlLink = htmlLink.substring(3, htmlLink.length());
        } else if (htmlLink.startsWith("./")) {
            url = htmlPageUrl.substring(0, htmlPageUrl.lastIndexOf("/") + 1);
            htmlLink = htmlLink.substring(2, htmlLink.length());
        }
        htmlLink = url + htmlLink;

        if (!htmlLink.startsWith("http://") && (!htmlLink.startsWith("https://"))) {
            htmlLink = "http://" + htmlLink;
        }

        if (htmlLink.contains("\\")) {
            htmlLink = htmlLink.replace("\\", "/");
        }
        StringBuilder sb = new StringBuilder(htmlLink);
        while (htmlLink.endsWith("/")) {
            htmlLink = sb.deleteCharAt(sb.length() - 1).toString();
        }

        return htmlLink;
    }

    /**
     * 执行下载并保存文件
     *
     * @param downloadFile
     * @param htmlLink
     */
    private void downloada(File downloadFile, String htmlLink) {

        new File(savePath).mkdirs();

        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        URL url;
        try {
            url = new URL(htmlLink);
            URLConnection conn = url.openConnection();
            in = new BufferedInputStream(conn.getInputStream());
            out = new BufferedOutputStream(new FileOutputStream(downloadFile));
            int b;
            byte buffer[] = new byte[10 * 1024];
            while ((b = in.read(buffer)) != -1) {
                out.write(buffer, 0, b);
            }
            out.flush();
            out.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("\n\n文件" + downloadFile.getName() + "下载完成，保存到：\n" + downloadFile.getParent());
    }

}


